# api/courses.py

from flask import Blueprint, request, jsonify
from models import db, Course, College

courses_bp = Blueprint('courses', __name__)

# 获得课程
@courses_bp.route('/api/courses', methods=['GET'])
def get_courses():
    college_id = request.args.get('college_id')
    if college_id:
        courses = Course.query.filter_by(college_id=college_id).all()
    else:
        courses = Course.query.all()

    result = [{
        # my new add
        'college_id':course.college_id,

        'course_id': course.course_id,
        'course_name': course.course_name,
        'college_name': College.query.get(course.college_id).college_name,
        'course_hours': course.course_hours
    } for course in courses]
    return jsonify(result)


# 增添课程
@courses_bp.route('/api/courses', methods=['POST'])
def add_course():
    data = request.get_json()

    if not data or 'course_name' not in data or 'college_id' not in data or 'course_hours' not in data:
        return jsonify({'message': 'Missing required fields'}), 400

    new_course = Course(
        course_name=data['course_name'],
        college_id=data['college_id'],
        course_hours=data['course_hours']
    )
    db.session.add(new_course)
    db.session.commit()

    return jsonify({
        'course_id': new_course.course_id,
        'course_name': new_course.course_name,
        'college_id': new_course.college_id,
        'course_hours': new_course.course_hours
    }), 201

# 更新课程
@courses_bp.route('/api/courses/<int:course_id>', methods=['PUT'])
def update_course(course_id):
    data = request.get_json()
    course = Course.query.get(course_id)

    if course:
        course.course_name = data['course_name']
        course.college_id = data['college_id']
        course.course_hours = data['course_hours']
        db.session.commit()
        return jsonify({'message': 'Course updated successfully'})

    return jsonify({'message': 'Course not found'}), 404


